package com.zhucx.utils;

import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Date;
import java.util.concurrent.*;

/**
 * 多线程下载
 *
 *
 */
public class DownloadURLFile {

    public static  String down(String href,String fileName,String savePath) throws InterruptedException
    {
//        System.out.println("正在下载："+href);
        long begin_time = new Date().getTime();
        URL url = null;
        try {
            url = new URL(href);
        } catch (MalformedURLException e1) {
            e1.printStackTrace();
        }

        URLConnection conn = null;
        try {
            conn = url.openConnection();
            //解决部分网站403
            conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
            // 设置请求超时为5s
            conn.setConnectTimeout(5 * 1000);
        } catch (IOException e1) {
            e1.printStackTrace();
        }

//        String fileName = url.getFile();
//
//        fileName = fileName.substring(fileName.lastIndexOf("/"));
//        System.out.println("开始下载>>>");
        int fileSize = conn.getContentLength();
//        System.out.println("文件总共大小：" + fileSize + "字节");

        // 设置分块大小
        int blockSize = 1024 * 1024;
        // 文件分块的数量
        int blockNum = fileSize / blockSize;

        if ((fileSize % blockSize) != 0) {
            blockNum += 1;
        }

//        System.out.println("分块数->线程数：" + blockNum);

        Thread[] threads = new Thread[blockNum];

        for (int i = 0; i < blockNum; i++) {

            // 匿名函数对象需要用到的变量
            final int index = i;
            final int finalBlockNum = blockNum;
            final String finalFileName = fileName;

            // 创建一个线程
            threads[i] = new Thread() {

                public void run() {
                    URL url = null;
                    try {
                        url = new URL(href);
                    } catch (MalformedURLException e1) {
                        // TODO Auto-generated catch block
                        e1.printStackTrace();
                    }
                    try {

                        // 重新获取连接
                        URLConnection conn = url.openConnection();
                        //解决部分网站403
                        conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
                        // 设置请求超时为5s
                        conn.setConnectTimeout(5 * 1000);
                        // 重新获取流
                        InputStream in = conn.getInputStream();
                        // 定义起始和结束点
                        int beginPoint = 0, endPoint = 0;

//                        System.out.print("第" + (index + 1) + "块文件：");
                        beginPoint = index * blockSize;

                        // 判断结束点
                        if (index < finalBlockNum - 1) {
                            endPoint = beginPoint + blockSize;
                        } else {
                            endPoint = fileSize;
                        }

//                        System.out.println("起始字节数：" + beginPoint + ",结束字节数：" + endPoint);

                        // 将下载的文件存储到一个文件夹中
                        //当该文件夹不存在时，则新建
                        File filePath = new File(savePath);
                        if (!filePath.exists()) {
                            filePath.mkdirs();
                        }
                        FileOutputStream fos = new FileOutputStream(new File(savePath, finalFileName + "_" + (index + 1)));

                        // 跳过 beginPoint个字节进行读取
                        in.skip(beginPoint);
                        byte[] buffer = new byte[1024];
                        int count;
                        // 定义当前下载进度
                        int process = beginPoint;
                        // 当前进度必须小于结束字节数
                        while (process < endPoint) {

                            count = in.read(buffer);
                            // 判断是否读到最后一块
                            if (process + count >= endPoint) {
                                count = endPoint - process;
                                process = endPoint;
                            } else {
                                // 计算当前进度
                                process += count;
                            }
                            // 保存文件流
                            fos.write(buffer, 0, count);

                        }
                        fos.close();
                        in.close();

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

            };
            threads[i].start();

        }

        // 当所有线程都结束时才开始文件的合并
        for (Thread t : threads) {
            t.join();
        }

        // 若该文件夹不存在，则创建一个文件夹
        File filePath = new File(savePath);
        if (!filePath.exists()) {
            filePath.mkdirs();
        }
        // 定义文件输出流
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(savePath + fileName);
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        for (int i = 0; i < blockNum; i++) {
            FileInputStream fis = null;
            try {
                fis = new FileInputStream(savePath + fileName + "_" + (i + 1));
//                fis = new FileInputStream(savePath + fileName );
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            byte[] buffer = new byte[1024];
            int count;
            try {
                while ((count = fis.read(buffer)) > 0) {
                    fos.write(buffer, 0, count);
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            try {
                fis.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }


        }
        try {
            fos.close();



        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally {
//            File delTmp = new File(savePath + fileName + "_" + (i + 1));
//            delTmp.delete();
        }

        long end_time = new Date().getTime();
        long seconds = (end_time - begin_time) / 1000;
        long minutes = seconds / 60;
        long second = seconds % 60;
//        System.out.println("下载完成,用时：" + minutes + "分" + second + "秒");
        return savePath+fileName;
    }


    public static boolean downFile(String href,String fileName,String savePath) throws InterruptedException{
        final ExecutorService exec = Executors.newFixedThreadPool(1);
           Callable call = new Callable() {

            public String call() throws Exception {

                //开始执行耗时操作
                down(href,fileName,savePath);
                return "线程执行完成.";

            }

        };

        Future future = null;

        try {

            future = exec.submit(call);

            String obj = (String) future.get(1000 * 10, TimeUnit.MILLISECONDS); //任务处理超时时间设为 10 秒

//            System.out.println("任务成功返回:" + obj);

        } catch (TimeoutException ex) {

//            System.out.println("处理超时啦....");

            ex.printStackTrace();

            future.cancel(true);

        } catch (Exception e) {

//            System.out.println("处理失败.");

            e.printStackTrace();

        }finally {

// 关闭线程池

//            System.out.println("关闭线程池");

            exec.shutdown();
//            deleteTmpFile(new File(savePath));

        }



        return true;
    }


//    public static void main(String[] args) throws Exception {
//        final ExecutorService exec = Executors.newFixedThreadPool(1);
//
//        Callable call = new Callable() {
//
//            public String call() throws Exception {
//
////开始执行耗时操作
//
//                down("https://cimg.fx361.com/images/2020/06/15/qkimageskatxkatx202010katx20201008-1-l.jpg","test.jpg","E:\\J_NEWS_DATA\\JNEWS\\j_news\\");
//
//                return "线程执行完成.";
//
//            }
//
//        };
//
//        Future future = null;
//
//        try {
//
//            future = exec.submit(call);
//
//            String obj = (String) future.get(1000 * 10, TimeUnit.MILLISECONDS); //任务处理超时时间设为 10 秒
//
//            System.out.println("任务成功返回:" + obj);
//
//        } catch (TimeoutException ex) {
//
//            System.out.println("处理超时啦....");
//
//            ex.printStackTrace();
//
//            future.cancel(true);
//
//        } catch (Exception e) {
//
//            System.out.println("处理失败.");
//
//            e.printStackTrace();
//
//        }finally {
//
//// 关闭线程池
//
//            System.out.println("关闭线程池");
//
//            exec.shutdown();
//
//        }
//    }


    /**
     * 查询文件
     * @param file
     * @throws IOException
     */
    public static boolean deleteTmpFile(File file)  {
        File[] files = file.listFiles();
        for (File file1 : files) {
            String name = file1.getName();
//            System.out.println(name);
            //if (file1.isFile()&&name.endsWith(".java")){
//            if (file1.isFile() && name.matches(".*\\.jpg_+d")) {
            if (file1.isFile() && name.matches(".*\\.jpg_.*")) {
//                System.out.println(name);
                file1.delete();
            }
        }
        return true;
    }



//    public static void main(String[] args) {
//        DownloadURLFile downloadURLFile = new DownloadURLFile();
//        try {
//            downloadURLFile.down("https://shop-1256119282.file.myqcloud.com/tooools/static/img/index/chrome/fatkun-4c36ca71b3.jpg","test.jpg","E:\\J_NEWS_DATA\\JNEWS\\j_news\\");
//        } catch (InterruptedException e) {
//            // TODO Auto-generated catch block
//            e.printStackTrace();
//        }
//    }
}